from src.config import Config
from threading import Thread
try:
    import mpv
except: pass

class Player: 

    def __init__(self):
        try:
            self.player = mpv.MPV(ytdl=True, input_default_bindings=True, input_vo_keyboard=True,
                              osc=True, load_scripts=True, config=True, terminal=False,
                              loglevel='', loop_playlist=True)
        except: self.player = None

        self.current_time       = 0
        self.current_time_text  = ""

    def start_playing(self, url: str, video=None, history=None):
        config = Config()

        self.player.speed = config.StandartVideoSpeed
        self.player.play(url)
        self.player.wait_for_playback()
        self.player.terminate()

        if video and history:
            history.remove(video)
            video.watched_time = int(self.current_time)
            history.insert(video)

    def play(self, url: str, play_option: str="", video=None, history=None, time_opt: str=""):
        config = Config()

        @self.player.property_observer('time-pos')
        def time_observer(_name, value):
            if value != None: 
                self.current_time = value
                self.current_time_text = "{:.2f}s".format(value)

        if play_option == "V": self.player.audio = False
        elif play_option == "A": self.player.video = False
            
        self.player.ytdl_format = f'bestvideo[height<={config.StandartVideoQuality}]+bestaudio/best'
        
        if video.watched_time != 0 and time_opt == "CN": 
            self.player.start = video.watched_time

        if config.WaitForVideoEnd or play_option == "A": 
            self.player.terminal = True
            self.player.input_terminal = True
            self.start_playing(url, video, history)
        else:
            thread = Thread(target=self.start_playing, args=(url, video, history))
            thread.start()

    def start_playlist(self, mirror: str, videos: list):
        for video in videos:
            url = mirror + "/watch?v=" + video.videoId
            self.player.playlist_append(url)
        self.player.playlist_pos = 0
        
        try: self.player.wait_for_property('idle-active')
        except mpv.ShutdownError: pass
        self.player.terminate()

    def play_playlist(self, mirror: str, play_option: str="", videos: list=[]):
        config = Config()

        if play_option == "V": self.player.audio = False
        elif play_option == "A": self.player.video = False
            
        self.player.ytdl_format = f'bestvideo[height<={config.StandartVideoQuality}]+bestaudio/best'

        if config.WaitForVideoEnd or play_option == "A": 
            self.player.terminal = True
            self.player.input_terminal = True
            self.start_playlist(mirror, videos)
        else:
            thread = Thread(target=self.start_playlist, args=(mirror, videos))
            thread.start()        

    def start_play_url_list(self, urls: list=list()):
        for url in urls:
            self.player.playlist_append(url)
        self.player.playlist_pos = 0
        
        try: self.player.wait_for_property('idle-active')
        except mpv.ShutdownError: pass
        self.player.terminate()

    def play_url_list(self, urls: list=list(), play_option: str=""):
        config = Config()

        if play_option == "V": self.player.audio = False
        elif play_option == "A": self.player.video = False
            
        self.player.ytdl_format = f'bestvideo[height<={config.StandartVideoQuality}]+bestaudio/best'

        if config.WaitForVideoEnd or play_option == "A": 
            self.player.terminal = True
            self.player.input_terminal = True
            self.start_play_url_list(urls)
        else:
            thread = Thread(target=self.start_play_url_list, args=(urls,))
            thread.start()  

if __name__ == "__main__":
    plr = Player()
    plr.play_video('https://yewtu.be/watch?v=MuTrvWB0JDE')
    print(f"Ended in: {plr.current_time}")
